package com.example.exp03.Service;


import com.example.exp03.Dao.CrawlingData;
import com.example.exp03.Model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

@Service
public class Mapp implements InitializingBean {

       public static List<RegionStats> allCoronaVirusData;

       static {
              allCoronaVirusData = new ArrayList<>();
       }

       @Override
       public void afterPropertiesSet() throws Exception {
              allCoronaVirusData = Mapp.getAllCoronaVirusData();
              System.out.println("成功获取数据");
       }
       public static List<RegionStats> getAllCoronaVirusData() throws IOException {
              List<RegionStats> all= new ArrayList<>();
              CrawlingData crawlingData = new CrawlingData();
              InputStream data=crawlingData.getData();
              Reader in = new InputStreamReader(data);
              Iterable<CSVRecord> records =CSVFormat.DEFAULT.withFirstRecordAsHeader()
                                  .withDelimiter(',')
                                  .withQuote('"')
                                  .withRecordSeparator("\r\n")
                                  .withIgnoreEmptyLines(true)
                                  .withAllowDuplicateHeaderNames(true)
                                  .parse(in);
              for(CSVRecord csvRecord : records){
                     String province = csvRecord.get("Province/State");
                     String country = csvRecord.get("Country/Region");
                     String total = csvRecord.get(csvRecord.size()-1);
                     String per = csvRecord.get(csvRecord.size()-2);
                     int t=Integer.parseInt(total);
                     int p=Integer.parseInt(per);
                     int d=t-p;
                     RegionStats regionStats = new RegionStats(province,country,t,d);
                     all.add(regionStats);
              }
              return all;
       }

}
